<script>
export default {
  name: 'OfficeSelect',
  props: {
    value: {
      type: [String, Number],
      default: ''
    },
    name: {
      type: [String],
      default: ''
    },
    time: {
      type: Array,
      default: () => []
    },
    othersRaw: {
      type: Object,
      default: () => ({})
    },
    disabled: {
      type: Boolean,
      default: false
    },
    apiFunc: {
      type: Function,
      required: true
    },
    otherValue: {
      type: String,
      default: ''
    },
    obj: {
      type: Object,
      default: () => ({
        value: 'agencyCode',
        name: 'agencyName',
        otherValue: 'officeId'
      })
    },
    emit: {
      type: [String, Boolean, Number, Object, Array],
      default: ''
    }
  },
  data() {
    return {
      optionsList: []
    }
  },
  watch: {
    time: {
      handler(v) {
        this.remoteGet('')
      }
    },
    emit: {
      handler(v) {
        this.remoteGet('')
      }
    }
  },
  created() {
    this.remoteGet('')
  },
  methods: {
    // 远程获取办事处
    remoteGet(v) {
      this.$emit('update:name', '')
      this.$emit('update:otherValue', '')
      this.$emit('input', '')
      if (this.disabled) { return }
      const otherRaw = {
        startDate: this.time[0],
        endDate: this.time[1],
        ...this.othersRaw
      }
      if (v !== '') {
        otherRaw[this.obj.name] = v
      }
      this.apiFunc([], otherRaw).then((res) => {
        this.optionsList = res
      })
    }
  },
  render(h) {
    const options = []
    for (const o of this.optionsList) {
      options.push(h('el-option', {
        props: {
          value: o[this.obj.value],
          label: o[this.obj.name]
        },
        key: o[this.obj.value]
      }))
    }
    return h(
      'el-select',
      {
        props: {
          value: this.value,
          ...this.$attrs,
          disabled: this.disabled,
          remote: true,
          remoteMethod: this.remoteGet
        },
        style: {
          width: '100%'
        },
        on: {
          change: v => {
            this.$emit('input', v)
            for (const o of this.optionsList) {
              if (v === o[this.obj.value]) {
                this.$emit('update:name', o[this.obj.name])
                this.$emit('update:otherValue', o[this.obj.otherValue] || '')
                return
              }
            }
            this.$emit('update:name', '')
            this.$emit('update:otherValue', '')
          }
        }
      },
      options
    )
  }
}
</script>
<style lang='scss' module>
.wrap {
}
</style>
